package com.heba.greenmulu.message;

import android.os.Build;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.notice.ItemFriendNoticeObject;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessHomePageActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.greenmulu.diary.ItemPersonHomePageActivity;
import com.heba.helper.DateHelper;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 好友通知列表
 * Created by jason on 2020/1/14.
 */
public class ItemNotificationFriendActivity extends BaseActivity {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;
    private TextView alertLB;
    private List<ItemFriendNoticeObject> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_notification_recycler);
        initTopbar();
        findViewById();
        initView();
        getFriendNoticeData();
    }

    @Override
    protected void findViewById() {
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
        alertLB = findViewById(R.id.alertLB);
        alertLB.setText(R.string.no_friend_notify);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.message_friends));
        txt_right.setVisibility(View.INVISIBLE);
        txt_right.setText(getResources().getString(R.string.message_notification_clear));

        list = new ArrayList<>();

        recycleAdapter = new QuickAdapter<ItemFriendNoticeObject>(list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_notification_friend_new;
            }

            @Override
            public void convert(VH holder, ItemFriendNoticeObject data, int position) {
                GlideUtil.loadImageWithPlaceHolderID(ItemNotificationFriendActivity.this, data.getIcon(), holder.getView(R.id.iv_avatar), R.drawable.icon_head_portrait);
                TextView tvContent = holder.getView(R.id.tv_content);
//                holder.setText(R.id.tv_name, data.getAccount());
//                holder.setText(R.id.tv_time, DateHelper.transferDateString(ItemNotificationFriendActivity.this, data.getTimeCreated()));
//                TextView tv_agree = holder.getView(R.id.tv_agree);
//                tv_agree.setVisibility(View.INVISIBLE);
//                holder.setText(R.id.tv_content, getResources().getString(R.string.message_friend_focus_text));

                String content = "<font color='#95cf63'>" + data.getAccount() + "</font>" + " " +
                        "<font color='#333333'>" + getResources().getString(R.string.message_friend_focus_text) + "</font>" + ". "
                        + "<font color='#a3a3a3'>" + DateHelper.transferDateString(ItemNotificationFriendActivity.this, data.getTimeCreated())
                        + "</font>";

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    tvContent.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_COMPACT));
                } else {
                    tvContent.setText(Html.fromHtml(content));
                }

                /**
                 * 關注用戶
                 */
//                tv_agree.setOnClickListener(v -> {
//                    loading.Start();
//                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
//                        @Override
//                        public void Success() {
//                            loading.End();
//                            ToastShow.displayToast(ItemNotificationFriendActivity.this, getResources().getString(R.string.mine_focus_user_success));
//                        }
//
//                        @Override
//                        public void Fail(String error) {
//                            loading.End();
//                        }
//                    }).followUser(ItemNotificationFriendActivity.this, data.getUserID());
//                });

                /**
                 * 跳轉用戶個人主頁
                 */
                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.SEND_USER_ID, data.getUserID());
                    if (data.getAccountType() == 0) {
                        openActivity(ItemPersonHomePageActivity.class, bundle);
                    }
                    else{
                        openActivity(BusinessPersonActivity.class,bundle);
                    }
                });

            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            getFriendNoticeData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getFriendNoticeData();
        });
    }

    /**
     * 獲取好友通知列表數據
     */
    private void getFriendNoticeData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/Notice/Follow", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemFriendNoticeObject> noticeObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemFriendNoticeObject>>() {
                                }.getType());
                                list.addAll(list.size(), noticeObjects);
                                alertLB.setVisibility(View.GONE);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                alertLB.setVisibility(View.VISIBLE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }
}
